import Layout from '@/views/layout/Layout'
import { GetSopNames } from '@/api/cms/aimodeltree'

/**
 * 生成SOP子路由
 * @param {Array} sopNames - SOP名称列表
 * @returns {Array} 生成的子路由配置
 */
function generateSOPChildrenRoutes(sopNames) {
  const children = []

  // 为每个SOP名称生成一个路由
  sopNames.forEach((sopName, index) => {
    const route = {
      path: `sop-${index + 1}`,
      component: () => import('@/views/aimodel/dynamicsop'),
      name: sopName,
      meta: {
        title: sopName,
        icon: getSopIcon(sopName),
        roles: ['ai_model_user', 'admin']
      },
      // 通过query参数传递SOP名称
      beforeEnter: (to, from, next) => {
        to.query.sop_name = sopName
        next()
      }
    }
    children.push(route)
  })

  // 添加SOP管理页面
  children.push({
    path: 'aimodeltreemanager/',
    component: () => import('@/views/aimodel/aimodeltreemanager'),
    name: 'SOP管理',
    meta: {
      title: 'SOP管理',
      icon: 'sop-manage',
      roles: ['ai_model_manager', 'admin']
    }
  })

  // 添加AI生成图片库页面
  children.push({
    path: 'ai-generated-images/',
    component: () => import('@/views/aimodel/ai-generated-images'),
    name: 'AI图片库',
    meta: {
      title: 'AI生成图片库',
      icon: 'image',
      roles: ['ai_model_user', 'admin']
    }
  })

  return children
}

/**
 * 根据SOP名称获取对应的图标
 * @param {string} sopName - SOP名称
 * @returns {string} 图标名称
 */
function getSopIcon(sopName) {
  const iconMap = {
    'B2B业务': 'b2b-business',
    '独立站SEO': 'seo',
    'linkedin运营': 'linkedin',
    'AI客服': 'ai-customer-service',
    '邮件营销': 'email-marketing',
    '社交媒体': 'social-media'
  }

  return iconMap[sopName] || 'ai-robot'
}

/**
 * 生成动态AI智能SOP子路由，用于内容管理模块
 * @returns {Promise<Array>} AI智能SOP子路由配置数组
 */
export async function generateAISOPChildrenRoutes() {
  try {
    const response = await GetSopNames()
    let sopNames = []

    if (response.data && response.data.success && response.data.data) {
      sopNames = response.data.data

      // 检查是否有项目权限
      if (sopNames.length === 0 && response.data.message) {
        console.warn('SOP权限检查:', response.data.message)
        // 如果没有项目权限，只返回提示页面和管理页面
        return [
          {
            path: 'no-project-access/',
            component: () => import('@/views/aimodel/NoProjectAccess'),
            name: '无项目权限',
            meta: {
              title: '无项目权限',
              icon: 'warning',
              noCache: true
            }
          },
          {
            path: 'aimodeltreemanager/',
            component: () => import('@/views/aimodel/aimodeltreemanager'),
            name: 'SOP管理',
            meta: { title: 'SOP管理', icon: 'sop-manage', roles: ['ai_model_manager', 'admin'] }
          },
          {
            path: 'ai-generated-images/',
            component: () => import('@/views/aimodel/ai-generated-images'),
            name: 'AI图片库',
            meta: {
              title: 'AI生成图片库',
              icon: 'image',
              roles: ['ai_model_user', 'admin']
            }
          }
        ]
      }
    } else if (response.data && Array.isArray(response.data)) {
      sopNames = response.data
    } else {
      // 默认SOP列表作为后备
      sopNames = ['B2B业务', '独立站SEO', 'linkedin运营']
    }

    console.log('获取到的SOP名称列表:', sopNames, '项目:', response.data?.project_name)

    // 生成SOP子路由
    return generateSOPChildrenRoutes(sopNames)
  } catch (error) {
    console.error('获取SOP名称失败，使用默认配置:', error)

    // 出错时使用默认配置
    const defaultSOPNames = ['B2B业务', '独立站SEO', 'linkedin运营']
    return generateSOPChildrenRoutes(defaultSOPNames)
  }
}

/**
 * 生成动态AI智能SOP路由（保留原有功能以防兼容性问题）
 * @returns {Promise<Object>} 动态路由配置
 */
export async function generateAISOPRoute() {
  try {
    const response = await GetSopNames()
    let sopNames = []

    if (response.data && response.data.success && response.data.data) {
      sopNames = response.data.data

      // 检查是否有项目权限
      if (sopNames.length === 0 && response.data.message) {
        console.warn('SOP权限检查:', response.data.message)
        // 如果没有项目权限，显示提示信息但保留SOP管理功能
        const sopRoute = {
          path: '/crm',
          component: Layout,
          redirect: '/crm/aimodeltreemanager/',
          name: '智能SOP',
          meta: {
            title: 'AI智能SOP',
            icon: 'ai-robot',
            roles: ['ai_model_user', 'admin']
          },
          alwaysShow: true,
          children: [
            {
              path: 'no-project-access/',
              component: () => import('@/views/aimodel/NoProjectAccess'),
              name: '无项目权限',
              meta: {
                title: '无项目权限',
                icon: 'warning',
                noCache: true
              }
            },
            {
              path: 'aimodeltreemanager/',
              component: () => import('@/views/aimodel/aimodeltreemanager'),
              name: 'SOP管理',
              meta: { title: 'SOP管理', icon: 'sop-manage', roles: ['ai_model_manager', 'admin'] }
            },
            {
              path: 'ai-generated-images/',
              component: () => import('@/views/aimodel/ai-generated-images'),
              name: 'AI图片库',
              meta: {
                title: 'AI生成图片库',
                icon: 'image',
                roles: ['ai_model_user', 'admin']
              }
            }
          ]
        }
        return sopRoute
      }
    } else if (response.data && Array.isArray(response.data)) {
      sopNames = response.data
    } else {
      // 默认SOP列表作为后备
      sopNames = ['B2B业务', '独立站SEO', 'linkedin运营']
    }

    console.log('获取到的SOP名称列表:', sopNames, '项目:', response.data?.project_name)

    // 生成动态路由
    const sopRoute = {
      path: '/crm',
      component: Layout,
      redirect: '/crm/sop-1',
      name: '智能SOP',
      meta: {
        title: 'AI智能SOP',
        icon: 'ai-robot',
        roles: ['ai_model_user', 'admin']
      },
      alwaysShow: true,
      children: generateSOPChildrenRoutes(sopNames)
    }

    return sopRoute
  } catch (error) {
    console.error('获取SOP名称失败，使用默认配置:', error)

    // 出错时使用默认配置
    const defaultSOPNames = ['B2B业务', '独立站SEO', 'linkedin运营']
    const sopRoute = {
      path: '/crm',
      component: Layout,
      redirect: '/crm/sop-1',
      name: '智能SOP',
      meta: {
        title: 'AI智能SOP',
        icon: 'ai-robot',
        roles: ['ai_model_user', 'admin']
      },
      alwaysShow: true,
      children: generateSOPChildrenRoutes(defaultSOPNames)
    }

    return sopRoute
  }
}

/**
 * 为现有路由数组替换AI智能SOP路由
 * @param {Array} routes - 现有路由数组
 * @returns {Promise<Array>} 更新后的路由数组
 */
export async function updateSOPRoutesInArray(routes) {
  try {
    const newSOPRoute = await generateAISOPRoute()

    // 查找并替换AI智能SOP路由
    const sopRouteIndex = routes.findIndex(route => route.name === '智能SOP')

    if (sopRouteIndex !== -1) {
      // 替换现有路由
      routes[sopRouteIndex] = newSOPRoute
      console.log('已更新AI智能SOP路由')
    } else {
      // 如果没找到，添加到数组中
      routes.push(newSOPRoute)
      console.log('已添加AI智能SOP路由')
    }

    return routes
  } catch (error) {
    console.error('更新SOP路由失败:', error)
    return routes
  }
}

export default {
  generateAISOPRoute,
  generateAISOPChildrenRoutes,
  updateSOPRoutesInArray,
  generateSOPChildrenRoutes,
  getSopIcon
}
